package comcast.yzhou;

import java.io.UnsupportedEncodingException;
import java.util.Random;
import java.util.UUID;

import com.fasterxml.uuid.EthernetAddress;
import com.fasterxml.uuid.Generators;
import com.fasterxml.uuid.StringArgGenerator;
import com.fasterxml.uuid.ext.FileBasedTimestampSynchronizer;
import com.fasterxml.uuid.impl.RandomBasedGenerator;
import com.fasterxml.uuid.impl.TimeBasedGenerator;

public class UUIDGenerationMethodCompare {
	private static final String NAME = "Comcast Cable";
	private static final int n = 250000;
	
    public static void main(String[] args) throws Exception {
    	
        // can either use bogus address; or local one, no difference perf-wise
        EthernetAddress nic = EthernetAddress.fromInterface();

        // Whether to include namespace? Depends on whether we compare with JDK (which does not)
        UUID namespaceForNamed = null;
    	
        final RandomBasedGenerator utilRandomGen = Generators.randomBasedGenerator(new Random());
        final TimeBasedGenerator timeGenPlain = Generators.timeBasedGenerator(nic);
        final StringArgGenerator nameGen = Generators.nameBasedGenerator(namespaceForNamed);
        
    	testJDK();
    	testJDKNames();
    	testRandom(utilRandomGen);
    	testTimeBased(timeGenPlain);
    	testNameBased(nameGen);
    	
    }
	
    private static final void testJDK()
    {
    	long start = System.currentTimeMillis();
        for (int i = 0; i < n; ++i) {
           UUID.randomUUID();
        }
        long end = System.currentTimeMillis();
        System.out.println("JDK random " + (end - start));
    }

    private static final void testJDKNames() throws UnsupportedEncodingException
    {
    	long start = System.currentTimeMillis();
        for (int i = 0; i < n; ++i) {
            final byte[] nameBytes = NAME.getBytes("UTF-8");
            UUID.nameUUIDFromBytes(nameBytes);
        }
        long end = System.currentTimeMillis();
        System.out.println("JDK name " + (end - start));
    }
    
    private static final void testRandom(RandomBasedGenerator uuidGen)
    {
    	long start = System.currentTimeMillis();
        for (int i = 0; i < n; ++i) {
            uuidGen.generate();
        }
        long end = System.currentTimeMillis();
        System.out.println("JDK java.util.Random " + (end - start));
    }

    private static final void testTimeBased(TimeBasedGenerator uuidGen)
    {
    	long start = System.currentTimeMillis();
        for (int i = 0; i < n; ++i) {
           uuidGen.generate();
        }
        long end = System.currentTimeMillis();
        System.out.println("JDK time-based " + (end - start));
    }
    
    private static final void testNameBased(StringArgGenerator uuidGen)
    {
    	long start = System.currentTimeMillis();
        for (int i = 0; i < n; ++i) {
            uuidGen.generate(NAME);
        }
        long end = System.currentTimeMillis();
        System.out.println("JDK name-based " + (end - start));
    }
}
